﻿using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Demo.Net.Dapper
{

    /// <summary>
    /// 一些通用方法封装
    /// </summary>
    public class DapperDbCom
    {

        private readonly IDbConnection _dbConnection;

        public DapperDbCom(IDbConnection dbConnection)
        {
            _dbConnection = dbConnection;
        }

        /// <summary>
        /// 异步方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public async Task<IEnumerable<T>> GetAllAsync<T>() where T : class
        {
  
            var sql = "SELECT * FROM " + GetTableName<T>();
            return await _dbConnection.QueryAsync<T>("SELECT * FROM " + GetTableName<T>());
        }

        public IEnumerable<T> GetAll<T>() where T : class
        {
            return  _dbConnection.Query<T>("SELECT * FROM " + GetTableName<T>());
        }

        public T GetById<T>(int id) where T : class
        {
            return _dbConnection.QuerySingleOrDefault<T>("SELECT * FROM " + GetTableName<T>() + " WHERE Id = @Id", new { Id = id });
        }

        public void Insert<T>(T entity) where T : class
        {
            var columns = GetColumns<T>();
            var values = "@" + string.Join(", @", columns);
            var sql = $"INSERT INTO {GetTableName<T>()} ({string.Join(", ", columns)}) VALUES ({values})";
            _dbConnection.Execute(sql, entity);
        }

        public void Update<T>(T entity) where T : class
        {
            var columns = GetColumns<T>().Select(c => $"{c} = @{c}");
            var sql = $"UPDATE {GetTableName<T>()} SET {string.Join(", ", columns)} WHERE Id = @Id";
            _dbConnection.Execute(sql, entity);
        }

        public void Delete<T>(int id) where T : class
        {
            var sql = $"DELETE FROM {GetTableName<T>()} WHERE Id = @Id";
            _dbConnection.Execute(sql, new { Id = id });
        }

        private static string GetTableName<T>()
        {
            return typeof(T).Name; // 表名为实体类名的复数形式
        }

        private static IEnumerable<string> GetColumns<T>()
        {
            return typeof(T).GetProperties().Where(p => p.Name != "Id").Select(p => p.Name);
        }

        //添加一些分页等等


    }
}
